<template>
  <div class="table-container">
    <div class="table-content">
      <el-table :data="tableData" border size="mini" highlight-current-row @row-mouse-enter="handleRowMouseEnter"
        @row-mouse-leave="handleRowMouseLeave" :cell-style="cellStyle" :header-cell-style="headerCellStyle">
        <el-table-column prop="count" label="器件总数" width="80" align="center"></el-table-column>
        <el-table-column prop="tag" label="器件分类数" width="80" align="center"></el-table-column>
        <el-table-column prop="data" label="出库/入库 流量" width="80" align="center"></el-table-column>
      </el-table>
    </div>

    <div class="chart-controls">
      <button class="refresh-btn" @click="fetchData" style="margin-right:auto;">刷新数据</button>

      <div style="display: flex; gap: 10px;">
        <button class="refresh-btn" @click="showDeleteDialog = true">删除器件</button>
        <button class="refresh-btn" @click="showUploadDialog = true">上传图片</button>
      </div>
      <el-dialog title="上传图片" :visible.sync="showUploadDialog" width="420px" :modal-append-to-body="false">
        <div style="max-height: 500px; overflow-y: auto; display: flex; flex-direction: column; gap: 18px;">
          <el-upload class="upload-demo" drag action="" :auto-upload="false" :show-file-list="true"
            :on-change="handleFileChange" :file-list="uploadFileList">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <el-input v-model="uploadName" placeholder="图片名称" />
          <el-select v-model="uploadFormat" placeholder="图片格式">
            <el-option label="jpg" value="jpg" />
            <el-option label="png" value="png" />
            <el-option label="jpeg" value="jpeg" />
            <el-option label="webp" value="webp" />
            <el-option label="bmp" value="bmp" />
            <el-option label="avif" value="avif" />
          </el-select>
          <div style="display: flex; flex-direction: row; gap: 12px; align-items: center;">
            <el-input v-model="tagInputs[0]" placeholder="特征1 (可选)" style="flex:1" size="small" />
            <el-input v-model="tagInputs[1]" placeholder="特征2 (可选)" style="flex:1" size="small" />
            <el-input v-model="tagInputs[2]" placeholder="特征3 (可选)" style="flex:1" size="small" />
          </div>
          <div style="display: flex; flex-direction: row; gap: 12px; align-items: center;">
            <el-input v-model="sizeInfo[0]" placeholder="长" style="flex:1" size="small" />
            <el-input v-model="sizeInfo[1]" placeholder="宽" style="flex:1" size="small" />
            <el-input v-model="sizeInfo[2]" placeholder="高" style="flex:1" size="small" />
          </div>
          器件描述
          <el-input type="textarea" :rows="3" v-model="uploadDesc" placeholder="" />
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showUploadDialog = false">取消</el-button>
          <el-button type="primary" @click="handleUploadConfirm">上传</el-button>
        </span>
      </el-dialog>
      <el-dialog title="删除元器件" :visible.sync="showDeleteDialog" width="520px" :modal-append-to-body="false" @open="fetchDeleteList">
        <div v-if="deleteLoading" style="text-align:center;padding:40px 0;">加载中...</div>
        <div v-else>
          <el-input v-model="deleteSearch" placeholder="搜索器件名称" clearable style="margin-bottom:12px;" size="small" />
          <div style="max-height: 340px; overflow-y: auto;">
            <el-radio-group v-model="selectedDeleteName" style="width:100%;">
              <div v-for="item in filteredDeleteList" :key="item" style="display:flex;align-items:center;gap:12px;margin-bottom:12px;">
                <el-radio :label="item" style="flex:1;">{{ item }}</el-radio>
                <img v-if="deleteImages[item]" :src="deleteImages[item]" alt="img" style="width:60px;height:60px;object-fit:cover;border-radius:6px;border:1px solid #eee;" />
                <span v-else style="width:60px;height:60px;display:inline-block;background:#f3f3f3;border-radius:6px;"></span>
              </div>
            </el-radio-group>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="danger" :disabled="!selectedDeleteName" @click="handleDeleteConfirm">删除</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
const deleteSearch = ref('');
const filteredDeleteList = computed(() => {
  if (!deleteSearch.value) return deleteList.value;
  return deleteList.value.filter(name => name && name.toLowerCase().includes(deleteSearch.value.toLowerCase()));
});
// 删除元器件弹窗相关
const showDeleteDialog = ref(false);
const deleteList = ref([]); // 器件名列表
const deleteImages = ref({}); // {name: imageUrl}
const selectedDeleteName = ref('');
const deleteLoading = ref(false);

// 获取可删除器件列表及图片
const fetchDeleteList = async () => {
  deleteLoading.value = true;
  deleteList.value = [];
  deleteImages.value = {};
  selectedDeleteName.value = '';
  try {
    const res = await axios.get('http://localhost:8080/project/normalRecommandExpand?count=15');
    if (Array.isArray(res.data)) {
      deleteList.value = res.data;
    } else if (Array.isArray(res.data.msg)) {
      deleteList.value = res.data.msg;
    }
    // 获取图片
    for (const name of deleteList.value) {
      axios.get(`http://localhost:8080/project/image/${encodeURIComponent(name)}`, { responseType: 'blob' })
        .then(imgRes => {
          const url = URL.createObjectURL(imgRes.data);
          deleteImages.value = { ...deleteImages.value, [name]: url };
        });
    }
  } catch (e) {
    deleteList.value = [];
  }
  deleteLoading.value = false;
};

// 删除确认
const handleDeleteConfirm = async () => {
  if (!selectedDeleteName.value) return;
  // 打印HTTP请求字符串（调试用）
  const url = `http://localhost:8080/project/deleteByName?name=${encodeURIComponent(selectedDeleteName.value)}`;
  let debugStr = `GET ${url}\n`;
  debugStr += 'Headers:\n  (default axios headers)\n';
  debugStr += 'Params:\n';
  debugStr += `  name: ${selectedDeleteName.value}\n`;
  console.log(debugStr);
  try {
    const res = await axios.get(url);
    if (res.data && res.data.code === 1) {
      alert('删除成功');
      showDeleteDialog.value = false;
      fetchData();
    } else {
      alert('删除失败: ' + (res.data && res.data.msg ? res.data.msg : '未知错误'));
    }
  } catch (e) {
    alert('删除异常: ' + e);
  }
};
import { ref, computed, onMounted } from 'vue'
import axios from 'axios';

// 表格数据
const tableData = ref([]);
const hoveredRow = ref(-1);

// 上传弹窗相关
const showUploadDialog = ref(false);
const uploadFileList = ref([]);
const uploadName = ref('');
const uploadFormat = ref('jpg');
const uploadDesc = ref('');
const tagInputs = ref(['', '', '']); // 三个特征输入
const sizeInfo = ref(['', '', '']); // 长宽高信息

const handleFileChange = (file, fileList) => {
  uploadFileList.value = fileList;
};

const handleUploadConfirm = async () => {
  if (!uploadFileList.value.length) {
    alert('请先选择图片文件');
    return;
  }
  if (!uploadName.value) {
    alert('请填写图片名称');
    return;
  }
  // 收集非空特征
  const tags = tagInputs.value.filter(t => t && t.trim() !== '');
  // 构造 FormData
  const formData = new FormData();
  formData.append('product.name', uploadName.value);
  formData.append('product.msg', uploadDesc.value);
  formData.append('product.img', uploadName.value + '.' + uploadFormat.value);
  formData.append('product.category', -1);
  formData.append('image', uploadFileList.value[0].raw);
  formData.append('productSize.name', uploadName.value)
  formData.append('productSize.length', sizeInfo.value[0])
  formData.append('productSize.width', sizeInfo.value[1])
  formData.append('productSize.height', sizeInfo.value[2])
  if (tags.length > 0) {
    formData.append('tags', JSON.stringify(tags));
  }

  // 打印HTTP请求字符串（调试用）
  let debugStr = 'POST http://localhost:8080/project/insert\n';
  debugStr += 'Headers:\n  Content-Type: multipart/form-data\n';
  debugStr += 'Body (FormData):\n';
  for (let pair of formData.entries()) {
    if (pair[1] instanceof File) {
      debugStr += `  ${pair[0]}: [File] name=${pair[1].name}, size=${pair[1].size}\n`;
    } else {
      debugStr += `  ${pair[0]}: ${pair[1]}\n`;
    }
  }
  console.log(debugStr);
  try {
    const res = await axios.post('http://localhost:8080/project/insert', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
    if (res.data.code === 1) {
      alert('上传成功');
      // showUploadDialog.value = false;
      // 清空表单
      uploadFileList.value = [];
      uploadName.value = '';
      uploadFormat.value = 'jpg';
      uploadDesc.value = '';
      tagInputs.value = ['', '', ''];
      sizeInfo.value = ['', '', ''];
    } else {
      alert('上传失败: ' + res.data.msg);
    }
  } catch (e) {
    alert('上传异常: ' + e);
  }
};

// 行鼠标进入事件
const handleRowMouseEnter = (row, column, event, rowIndex) => {
  hoveredRow.value = rowIndex;
};

// 行鼠标离开事件
const handleRowMouseLeave = () => {
  hoveredRow.value = -1;
};

// 单元格样式
const cellStyle = ({ rowIndex }) => {
  return {
    padding: '8px 12px',
    backgroundColor: hoveredRow.value === rowIndex ? '#eef2ff' : ''
  };
};

// 表头样式
const headerCellStyle = () => {
  return {
    padding: '8px 12px',
    backgroundColor: '#f8fafc',
    color: '#475569',
    fontWeight: '600'
  };
};

// 读取数据
async function fetchData() {
  var count, tag, data;
  try {
    await axios.get('http://localhost:8080/project/getAllCount')
      .then(response => {
        count = response.data.msg; // 一共有多少器件
      })
      .catch(error => {
        console.error('请求出错:', error);
      });

    await axios.get('http://localhost:8080/project/rating')
      .then(response => {
        data = response.data.msg;  // 进出流量
      })
      .catch(error => {
        console.error('请求出错:', error);
      });

    await axios.get('http://localhost:8080/project/getCount')
      .then(response => {
        tag = response.data.msg; // 器件种类
      })
      .catch(error => {
        console.error('请求出错:', error);
      });

    var newData = [{
      count: count,
      tag: tag,
      data: data
    }];

    tableData.value = newData;
  } catch (error) {
    console.error('async/await 请求出错:', error);
    throw error; // 可以将错误向上抛出
  }
}

// 初始化数据
fetchData();
</script>

<style scoped>
/* D2Admin风格卡片 */
.table-container {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  max-width: 800px;
  margin: 2rem auto;
  padding: 0.5rem;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.chart-controls {
  display: flex;
  justify-content: space-between;
  margin-top: 0.5rem;
  padding: 0.5rem;
}

.refresh-btn {
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0.5rem 1rem;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  transition: background-color 0.2s ease;
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px;
  height: 48px;
}

.card-title {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
}

.card-actions {
  display: flex;
  gap: 8px;
}

/* 表格内容区 */
.table-content {
  padding: 0 16px 16px;
}

/* 表格底部信息区 */
.table-footer {
  padding: 12px 16px;
  border-top: 1px solid #e5e7eb;
  background-color: #f9fafb;
}

/* 数据统计信息 */
.data-count {
  margin: 0;
  color: #64748b;
}

/* 适配D2Admin的响应式调整 */
@media (max-width: 768px) {
  .d2-card {
    margin: 8px;
  }

  .table-content {
    padding: 0 8px 8px;
  }
}
</style>
